﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SuperKit
{
    public enum FastCatalogItemType {
        Directory,
        File,
        Image,
        Video,
    }


    [Flags]
    public enum FastCatalogFilter {
        None = 0,
        File = 1, // 文件，如果配置此项目，则包含所有文件（即不会再检查Image或Video）
        Folder = 2, // 文件夹
        Image = 4, // 如果配置此项目，那么如果文件是图片，则加入
        Video = 8, // 如果配置此项目，那么如果文件是视频，则加入
    }


    public class GalleryManager {
        public const int COLUMN_TYPE = 0;
        public const int COLUMN_NAME = 1;

        public static ConfigReader Cfg => ConfigReader.Instance;

        public GalleryWindow Owner { get; }
        public ListView OwnerList { get; }
        public TextBox OwnerAdditionText { get; }
        public TextBox OwnerRenameText { get; }

        private GridViewColumn headerFile;

        public bool LockRefresh { get; set; }
        public string DirPath { get; set; }

        public int ThumbCatalogIndex => Cfg.CatalogIndex;

        public ObservableCollection<GalleryFileViewModel> Items { get; set; }
        private List<GalleryFileViewModel> RenameList { get; set; }
        public GalleryFileViewModel CurrentItem { get; set; }
        private int CurrentIndex { get; set; }
        private MenuItem menu_Catalog;

        public GalleryManager(GalleryWindow owner, ListView list, GridViewColumn headerFile, TextBox additionText, TextBox renameText) {
            this.Owner = owner;
            this.OwnerList = list;
            this.OwnerAdditionText = additionText;
            this.OwnerRenameText = renameText;
            this.headerFile = headerFile;

            renameText.KeyDown += RenameText_KeyDown;
            OwnerList.KeyDown += OwnerList_KeyDown;
        }

        private void OwnerList_KeyDown(object sender, KeyEventArgs e) {

            if (e.Key == Key.Enter) {
                e.Handled = true;
                ToggleState();
            } else if ((int)e.Key >= (int)Key.D0 && (int)e.Key <= (int)Key.D9) {
                e.Handled = true;
                int number = e.Key - Key.D0;
                SetState(number);
            } else if (e.Key == Key.Oem3) {
                e.Handled = true;
                SetState(0);
            } else if (e.Key == Key.R) {
                e.Handled = true;
                ButtonBatchRename_Click(null, null);
            } else if (e.Key == Key.C) {
                e.Handled = true;
                Owner.Combine_Click(null, null);
            } else {

            }
        }
        private void RenameText_KeyDown(object sender, KeyEventArgs e) {
            if (e.Key == Key.Enter) {
                ButtonRename_Click(null, null);
            }
        }

        private void OwnerList_SelectedIndexChanged(object sender, EventArgs e) {
            if (OwnerList.SelectedItems.Count == 0) {
                return;
            }

            CurrentIndex = OwnerList.SelectedIndex; // OwnerList.SelectedItems[0];
            CurrentItem = Get(CurrentIndex);
            OwnerRenameText.Text = CurrentItem.GetFileName();
        }


        private void OwnerList_DoubleClick(object sender, EventArgs e) {
            ToggleState();
        }


        public void Load(string dirPath) {
            DirPath = dirPath;

            var dir_items = new List<GalleryFileViewModel>();
            var file_items = new List<GalleryFileViewModel>();

            DirectoryInfo info = new DirectoryInfo(dirPath);
            var dirs = info.GetDirectories();
            var files = info.GetFiles();
            if (dirs != null) {
                foreach (var i in dirs) {
                    // 跳过隐藏目录
                    if (i.Name.IndexOf("(_") == 0) {
                        continue;
                    }

                    dir_items.Add(new GalleryFileViewModel(i.FullName, true));
                }
            }
            if (files != null) {
                foreach (var i in files) {
                    file_items.Add(new GalleryFileViewModel(i.FullName, false));
                }
            }

            // 排序
            dir_items.Sort((a, b) => { return string.Compare(a.FullName, b.FullName); });
            file_items.Sort((a, b) => { return string.Compare(a.FullName, b.FullName); });

            Items = new ObservableCollection<GalleryFileViewModel>();
            foreach (var item in dir_items) {
                Items.Add(item);
            }
            foreach (var item in file_items) {
                Items.Add(item);
            }

            OwnerList.ItemsSource = Items;

            headerFile.Header = $"文件({OwnerList.Items.Count})";
        }




        public void ToggleState() {
            foreach (var i in OwnerList.SelectedItems) {
                GalleryFileViewModel dir = i as GalleryFileViewModel;
                if (Kit.IsEmpty(dir.Catalog)) {
                    dir.Catalog = GetCatalog(0);
                } else {
                    dir.Catalog = string.Empty;
                }
            }
        }

        private string GetCatalog(int id) {
            var arr = Cfg.CatalogArray;
            string catalog = string.Empty;
            if (id >= 0 && id < arr.Length) {
                catalog = arr[id];
            }
            return catalog;
        }

        private void SetState(int id) {
            SetState(GetCatalog(id));
        }

        public void SetState(string text) {
            foreach (var i in OwnerList.SelectedItems) {
                GalleryFileViewModel dir = i as GalleryFileViewModel;
                dir.Catalog = text;
            }
        }




        public GalleryFileViewModel Get(int index) {
            return Items[index];
        }


        public void Reload() {
            Load(DirPath);
        }


        public void ExecuteSelection() {

            foreach (var i in Items) {
                if (Kit.IsEmpty(i.Catalog)) {
                    continue;
                }

                string catalogName = $"(_{i.Catalog})";
                DirectoryInfo container = new DirectoryInfo(Path.Combine(DirPath, catalogName));
                if (container.Exists == false) {
                    container.Create();
                }

                string newPath = Path.Combine(container.FullName, Path.GetFileName(i.FullName));
                if (Directory.Exists(newPath)) {
                    continue;
                }

                try {
                    Directory.Move(i.FullName, newPath);
                } catch (Exception e) {
                    Log(e.Message);
                }
            }

            Reload();
        }


        /// <summary>
        /// 此功能执行多个目录之间的合并。
        /// 从多个目录中选择相同的文件名部分。然后新建一个目录，将所有文件放进去。
        /// </summary>
        public void ExecuteFastCombine() {
            // 得到已经选中的项目
            var list = new List<GalleryFileViewModel>();
            foreach (var i in OwnerList.SelectedItems) {
                list.Add(Items[(int)i]);
            }

            if (list.Count < 2) {
                Log("请至少选择两个项目！");
                return;
            }

            // 根据选中的项目，得到最长的名称
            var desiredName = GetSeriesName(list);

            DirectoryInfo container = new DirectoryInfo(Path.Combine(DirPath, desiredName));
            if (container.Exists == false) {
                container.Create();
            }

            // 移动所有项目
            foreach (var i in list) {
                var newPath = Path.Combine(container.FullName, Path.GetFileName(i.FullName));
                Directory.Move(i.FullName, newPath);
            }

            Log(desiredName);

            Reload();
            Kit.Beep();
        }

        private void Log(string msg) {
            
        }

        private string GetSeriesName(List<GalleryFileViewModel> list) {
            int min = 256;
            int same = 0;
            int totalFiles = 0;
            foreach (var item in list) {
                min = Math.Min(min, Path.GetFileName(item.FullName).Length);
                DirectoryInfo info = new DirectoryInfo(item.FullName);
                totalFiles += Kit.Len(info.GetFiles());
            }

            List<string> names = new List<string>(list.Count);
            foreach (var i in list) {
                names.Add(Path.GetFileName(i.FullName));
            }

            string first = names[0];
            bool isNotEqual = false;
            for (int i = 0; i < min; i++) {
                same = i;
                for (int n = 1; n < names.Count; n++) {
                    if (names[n][i] != first[i]) {
                        isNotEqual = true;
                        break;
                    }
                }
                if (isNotEqual) {
                    break;
                }
            }

            string desiredName = first.Substring(0, same);
            // 特殊处理，删除Vol.项目
            desiredName = desiredName.Replace("Vol.", "");
            // 特殊处理，删除双空格项目
            desiredName = desiredName.Replace("  ", " ");

            return desiredName.Trim() + string.Format("[{0}-{1}][{2}P]", 1, list.Count, totalFiles);
        }



        public void SetFavorStar() {
            foreach (var i in OwnerList.SelectedItems) {
                SetMark((GalleryFileViewModel)i, Kit.FAVOR_START);
            }
        }

        public void AddAddition(string text, bool isFront) {

            foreach (var i in OwnerList.SelectedItems) {
                SetMark((GalleryFileViewModel)i, text, isFront);
            }
        }

        public void SetMark(GalleryFileViewModel item, string mark, bool isFront = true) {
            if (Kit.IsEmpty(mark)) {
                return;
            }
            var name = Path.GetFileNameWithoutExtension(item.FullName);
            var ext = Path.GetExtension(item.FullName);
            // 如果有星标，则消除，没有星标，则增加
            if (name.IndexOf(mark) != -1) {
                name = name.Replace(mark, "");
            } else {
                if (isFront) {
                    name = mark + name;
                } else {
                    name = name + mark;
                }
            }

            name = name + ext;


            var path = Path.Combine(Path.GetDirectoryName(item.FullName), name);
            if (Directory.Exists(path)) {
                Log($"{path} 已经存在！");
                return;
            }

            try {
                Owner.CancelLoad();
                Directory.Move(item.FullName, path);
            }catch (IOException ex) {
                MessageBox.Show(ex.Message, "警告");
                return;
            }
            

            // 刷新项目
            item.FullName = path;
            //OwnerList.Items[idx].SubItems[COLUMN_NAME].Text = item.Name;
            OwnerRenameText.Text = Path.GetFileNameWithoutExtension(item.Name);
        }


        public void SetupRename(Button buttonRename, Button buttonBatchRename) {
            buttonRename.Click += ButtonRename_Click;
            buttonBatchRename.Click += ButtonBatchRename_Click;
        }


        private void ButtonRename_Click(object sender, System.Windows.RoutedEventArgs e) {
            if (CurrentItem == null || Kit.IsEmpty(OwnerRenameText.Text)) {
                return;
            }
            if (CurrentItem.IsDirectory) {
                DirectoryInfo info = new DirectoryInfo(CurrentItem.FullName);
                var newPath = Path.Combine(info.Parent.FullName, OwnerRenameText.Text);
                if (Directory.Exists(newPath)) {
                    Log($"目录 {OwnerRenameText.Text} 已经存在！");
                    return;
                }
                Directory.Move(CurrentItem.FullName, newPath);
                CurrentItem.FullName = newPath;
            } else {
                FileInfo info = new FileInfo(CurrentItem.FullName);
                var newPath = Path.Combine(info.Directory.FullName, OwnerRenameText.Text);
                if (File.Exists(newPath)) {
                    Log($"文件 {OwnerRenameText.Text} 已经存在！");
                    return;
                }
                File.Move(CurrentItem.FullName, newPath);
                CurrentItem.FullName = newPath;
            }
        }


        private void ButtonBatchRename_Click(object sender, System.Windows.RoutedEventArgs e) {
            BatchRename dlg = new BatchRename();
            RenameList = new List<GalleryFileViewModel>();
            foreach (var i in OwnerList.SelectedItems) {
                var item = i as GalleryFileViewModel;
                dlg.Add(item.FullName);
                RenameList.Add(item);
            }

            dlg.Callback = (index, name, newName) => {
                RenameList[index].FullName = newName;
            };

            dlg.ShowDialog();
        }

    }
}
